package com.treeliked.udpdemo.service.impl;

import com.treeliked.udpdemo.model.Constant;
import com.treeliked.udpdemo.model.Message;
import com.treeliked.udpdemo.service.UdpService;
import com.treeliked.udpdemo.util.MessageUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
import java.util.Objects;

/**
 * 抽象发送服务实现
 *
 * @author lss
 * @date 2019-01-03, Thu
 */
public abstract class AbstractUdpServiceImpl implements UdpService {

    private DatagramSocket ds;

    AbstractUdpServiceImpl(DatagramSocket ds) {
        this.ds = ds;
    }

    @Override
    public void send(Message msg) throws IOException {
        msg.setSendTime(new Date());
        byte[] bytes = new byte[Constant.BUFFER_SIZE];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), msg.getDestPost());
        packet.setData(Objects.requireNonNull(MessageUtils.messageToBytes(msg)));
        ds.send(packet);
    }
}
